package com.business.system.task;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import com.business.system.bean.SettleLogBean;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.service.Service;

import net.sf.rose.util.DateFormat;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.business.system.util.DBTools;

/**
 * @author: xudy
 * @date: 2018/04/07 15:24
 * @description:
 */
@Component
public class SettleTask {
	private static final Logger LOG = Logger.getLogger(SettleTask.class);

	/**
	 * 结算管理
	 * 每月7号凌晨1点执行一次(防止出现意外情况)
	 */
	@Scheduled(cron = "0 0 1 7 * ?")
	//@Scheduled(cron = "30 * * * * ?")
	public void calcSettle() {
		// 1.按照月份,用户进行统计
		// 2.统计推荐返利,代理返利,应结算金额
		// 3.同时将对应的推荐返利和代理返利表的数据设置成已结算
		LOG.error("开始月度结算功能.........");
		Service service = new Service();
		try {
            // 获取当前日期
			Calendar c1 = Calendar.getInstance();
            c1.add(Calendar.MONTH, -1);
            //设置为1号,当前日期既为本月第一天
            c1.set(Calendar.DAY_OF_MONTH,1);
            c1.set(Calendar.HOUR_OF_DAY,0);
            c1.set(Calendar.MINUTE,0);
            c1.set(Calendar.SECOND,0);
            String date00 = DateFormat.format(c1.getTime(),DateFormat.DATE_FORMAT_3);
            c1.add(Calendar.MONTH, 1);
            String dateNext00 = DateFormat.format(c1.getTime(),DateFormat.DATE_FORMAT_3);
			// 1.获取上月尚未结算的代理记录
			String backFeeAgentLogSql = "select sum(back_fee) as sums,user_id from back_fee_log where state=1 and type=1 and create_time>=? and create_time<? group by user_id order by user_id";
			List<Map<String, Object>> fee1 = DBTools.getDataList(service, backFeeAgentLogSql, date00,dateNext00);
			// 2.获取上月尚未推荐的返利记录
			String backFeeRecommendLogSql = "select sum(back_fee) as sums,user_id from back_fee_log where state=1 and type=2 and create_time>=? and create_time<? group by user_id order by user_id";
            List<Map<String, Object>> fee2 = DBTools.getDataList(service, backFeeRecommendLogSql, date00,dateNext00);
            // 3.获取全部的用户
            String userSql = "select user_id from back_fee_log where state=1 and type=2 and create_time>=? and create_time<? group by user_id order by user_id";
			List<Map<String,Object>> users = DBTools.getDataList(service,userSql,date00,dateNext00);
            int i = 0 ;
			for(Map<String,Object> user : users){
                SettleLogBean settle = new SettleLogBean();
			    String userId = user.get("user_id").toString();
                settle.setUserId(userId);
			    for(Map<String, Object> f1 :fee1){
                    if(userId.equals(f1.get("user_id"))){
                        settle.setAgentFee(Double.parseDouble(f1.get("sums").toString()));
                        break;
                    }
                }
                for(Map<String, Object> f2 :fee2){
                    if(userId.equals(f2.get("user_id"))){
                        settle.setRecommendFee(Double.parseDouble(f2.get("sums").toString()));
                        break;
                    }
                }
                //计算总费用
                settle.setTotalFee(settle.getAgentFee() + settle.getRecommendFee());
                settle.setStaticTime(DateFormat.format(date00,DateFormat.DATE_FORMAT_3));
                settle.setCreateUser("system");
                settle.setUpdateUser("system");
                i+=DBUtils.update(service,settle);
            }
            if(i==users.size()){
                String updateSql ="update back_fee_log set state=2 where state=1 and create_time>=? and create_time<?";
                int j = DBTools.updateSql(service,updateSql,date00,dateNext00);
                if(j>0){
                    LOG.error(">>>>>>>返利日志更新成功");
                    LOG.error(">>>>>>>月度统计成功插入");
                    service.commit();
                }else{
                    LOG.error("<<<<<<<!!!返利日志更新失败!!!");
                }
            }else{
                LOG.error("<<<<<<<!!!月度统计插入异常!!!");
                service.rollback();
            }

		} catch (Exception e) {
			service.rollback();
			e.printStackTrace();
			LOG.error(e.getMessage(), e);
		} finally {
			service.close();
		}
		LOG.error(">>>>>>>结束月度结算功能");
	}
}